package service

import (
	"server/global"
	"server/model"

	"gorm.io/gorm"
)

//  get
func DeviceLogFetch(maps map[string]interface{}) (int64, []*model.DeviceLog, error) {
	var logs []*model.DeviceLog
	var total int64
	err := global.DB.Model(&model.DeviceLog{}).Where("device_id = ? AND created_at BETWEEN ? AND ?",
		maps["device_id"],
		maps["start_time"],
		maps["end_time"]).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return 0, nil, err
	}
	err = global.DB.Raw("SELECT * FROM device_logs WHERE device_id = ? AND created_at BETWEEN ? AND ? LIMIT ? OFFSET ? ",
		maps["device_id"],
		maps["start_time"],
		maps["end_time"],
		maps["page_size"],
		maps["page"]).Order("created_at desc").Scan(&logs).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return 0, nil, err
	}

	return total, logs, nil
}

func DeviceLogAdd(d model.DeviceLog) error {
	if err := global.DB.Create(&d).Error; err != nil {
		return err
	}
	return nil

	// device := map[string]interface{}{
	// 	"device_id":  a.DeviceID,
	// 	"value":      a.Value,
	// 	"status":     a.Status,
	// 	"created_at": time.Now(),
	// 	"updated_at": time.Now(),
	// }

	// if err := models.AddDeviceLog(device); err != nil {
	// 	return err
	// }

	// return nil
}
